package com.english_test_sys.controller;

import com.english_test_sys.pojo.WrongQuestion;
import com.english_test_sys.service.WrongQuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/wrong-questions")
public class WrongQuestionController {

    @Autowired
    private WrongQuestionService wrongQuestionService;

    @PostMapping
    public ResponseEntity<?> addOrUpdateWrongQuestion(@RequestBody WrongQuestion wrongQuestion) {
        try {
            // 1. 检查是否已存在相同记录
            WrongQuestion existing = wrongQuestionService.getWrongQuestionByUserAndQuestion(
                    wrongQuestion.getUserId(),
                    wrongQuestion.getQuestionId()
            );

            // 2. 如果已存在，则更新错误次数
            if (existing != null) {
                existing.setWrongCount(existing.getWrongCount() + 1);
                existing.setUserAnswer(wrongQuestion.getUserAnswer());
                wrongQuestionService.updateWrongQuestion(existing);
                return ResponseEntity.ok(existing);
            }

            // 3. 不存在则新增
            WrongQuestion savedQuestion = wrongQuestionService.addWrongQuestion(wrongQuestion);
            return ResponseEntity.ok(savedQuestion);

        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "操作失败: " + e.getMessage()));
        }
    }


    @PutMapping
    public ResponseEntity<?> updateWrongQuestion(@RequestBody WrongQuestion wrongQuestion) {
        try {
            boolean result = wrongQuestionService.updateWrongQuestion(wrongQuestion);
            return result ? ResponseEntity.ok(wrongQuestion)
                    : ResponseEntity.badRequest().body(Map.of("error", "更新失败"));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(Map.of("error", "更新失败: " + e.getMessage()));
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getWrongQuestionById(@PathVariable int id) {
        try {
            WrongQuestion question = wrongQuestionService.getWrongQuestionById(id);
            if (question == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("{\"message\":\"Question not found\"}");
            }
            return ResponseEntity.ok(question);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    @GetMapping("/user/{userId}")
    public List<WrongQuestion> getWrongQuestionsByUserId(@PathVariable int userId) {
        return wrongQuestionService.getWrongQuestionsByUserId(userId);
    }

    @GetMapping("/user/{userId}/category/{category}")
    public List<WrongQuestion> getWrongQuestionsByUserIdAndCategory(
            @PathVariable int userId, @PathVariable String category) {
        return wrongQuestionService.getWrongQuestionsByUserIdAndCategory(userId, category);
    }

    @GetMapping("/user/{userId}/question/{questionId}")
    public ResponseEntity<?> getWrongQuestionByUserAndQuestion(
            @PathVariable int userId, @PathVariable int questionId) {
        try {
            WrongQuestion question = wrongQuestionService.getWrongQuestionByUserAndQuestion(userId, questionId);
            if (question == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND)
                        .body("{\"message\":\"Question not found\"}");
            }
            return ResponseEntity.ok(question);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("{\"error\":\"" + e.getMessage() + "\"}");
        }
    }

    @PutMapping("/increment/{id}")
    public boolean incrementWrongCount(@PathVariable int id) {
        return wrongQuestionService.incrementWrongCount(id);
    }
    @PutMapping("/{id}/notes")
    public ResponseEntity<?> updateNotes(
            @PathVariable int id,
            @RequestBody Map<String, String> request) {
        try {
            WrongQuestion question = wrongQuestionService.getWrongQuestionById(id);
            if (question == null) {
                return ResponseEntity.notFound().build();
            }

            question.setNotes(request.get("notes"));
            boolean result = wrongQuestionService.updateWrongQuestion(question);

            return result ? ResponseEntity.ok(question)
                    : ResponseEntity.badRequest().body("更新笔记失败");
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("更新笔记失败: " + e.getMessage());
        }
    }

}
